package com.personal.system.listener.mq;

import com.personal.model.system.SysUser;
import com.personal.system.entity.seckill.SeckillGoods;
import com.personal.system.entity.seckill.SeckillOrder;
import com.personal.system.service.SeckillService;
import com.personal.system.constant.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Slf4j
@Service
public class MQReceiver {

    @Resource
    SeckillService goodsService;

    @RabbitListener(queues = "seckill.queue")
    public void receive(String message) {
        log.info("收到消息:" + message);

        SeckillMessage mm = RedisService.stringToBean(message, SeckillMessage.class);
        SysUser user = mm.getUser();
        long goodsId = mm.getGoodsId();

        SeckillGoods goods = goodsService.getById(goodsId);
        if (goods.getStockCount() <= 0) return;

        //判断是否已经秒杀到了
        SeckillOrder order = goodsService.getOrderByUserNameGoodsId(user.getId(),goodsId);
        if (order != null) return;

        //减库存 下订单 写入秒杀订单
        goodsService.insert(user, goods);
    }

}
